#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
# @Time: 2023/9/23 12:07
# @Author: Anthony (anthony66888@163.com)
# @description:
"""
import datetime
import random
import threading
import time
import traceback
from urllib import parse

import requests

from auto_battle_room import YamlControl


class AutoCreateRoll:
    def __init__(self):
        """获取"""
        self.config_data = YamlControl("/data/config.yaml").read_yaml()  # 读取配置项
        self.host = self.config_data["admin_host"]  # 获取环境域名
        self.token = self.config_data["admin_token"]  # 获取后台token

        self.post_headers = {
            "Token": self.token,
            "Content-Type": "application/x-www-form-urlencoded"
        }
        self.get_headers = {
            "Token": self.token
        }

        self.now_date = datetime.datetime.now().strftime("%Y-%m-%d")  # 获取当前日期
        self.next_date = (datetime.datetime.now() + datetime.timedelta(days=1)).strftime("%Y-%m-%d")  # 获取明天日期

        # 读取roll房配置项
        roll_basic_config = YamlControl("/data/roll_config.yaml").read_yaml()
        self.roll_config_list = roll_basic_config["roll_config"]["roll_config"]
        self.gift_config = roll_basic_config["roll_config"]["gift_config"]
        self.target_roll_name_list = roll_basic_config["target_roll_name_list"]

    def create_roll(self, roll_config):
        """创建roll房"""
        url = '/api/sys/roll/addRollRoom'
        if roll_config["rechargeStartTime"] is None:
            roll_config["rangeTime[0]"] = self.now_date + " 00:00:00"
            roll_config["rangeTime[1]"] = self.next_date + " 00:00:00"
            roll_config["openTime"] = self.next_date + " " + roll_config["openTime"]
            roll_config["rechargeStartTime"] = self.now_date + " 00:00:00"
            roll_config["rechargeEndTime"] = self.next_date + " 00:00:00"
        data = parse.urlencode(roll_config)
        try:
            response = requests.post(url=self.host + url, data=data, headers=self.post_headers)
            print("创建roll房成功")
            return response.json()

        except Exception as e:
            print(f"创建roll房报错：{e}")
            traceback.print_exc()
            return None

    def get_roll_list(self):
        """获取roll房列表"""
        url = '/api/sys/roll/page'
        data = {
            "page": 1,
            "pageSize": 100,
            "state": 0,
            "current": 1
        }
        try:
            response = requests.get(url=self.host + url, params=data, headers=self.get_headers).json()
            roll_lists = []
            for target_roll_name in self.target_roll_name_list:
                match = next((roll for roll in response["data"]["pageData"] if roll["title"] == target_roll_name), None)
                if match is not None:
                    roll_lists.append(match)
            print("获取roll房列表成功")
            return roll_lists
        except Exception as e:
            print(f"获取roll房列表报错：{e}")
            traceback.print_exc()
            return []

    def add_gift(self, gift_config, roll_id=None):
        """添加roll饰品"""
        url = '/api/sys/roll/addGift'
        if gift_config["rollId"] is None:
            gift_config["rollId"] = roll_id
        data = parse.urlencode(gift_config)
        try:
            response = requests.post(url=self.host + url, data=data, headers=self.post_headers)
            print("添加roll饰品成功")
            return response.json()
        except Exception as e:
            print(f"添加roll饰品报错：{e}")
            traceback.print_exc()
            return None

    def open_roll(self, roll_id):
        """开启roll房"""
        url = "/api/sys/roll/show"
        data = {
            "rollId": roll_id,
            "state": 1
        }
        data = parse.urlencode(data)
        try:
            requests.post(url=self.host + url, data=data, headers=self.post_headers)
            print("开启roll房成功")
        except Exception as e:
            print(f"开启roll房报错：{e}")
            traceback.print_exc()


def create_roll():
    auto_create_roll = AutoCreateRoll()
    # 生成roll房间
    for roll_config in auto_create_roll.roll_config_list:
        response = auto_create_roll.create_roll(roll_config)
        print("创建roll房间：", response)
    # 获取roll房间id
    roll_list = auto_create_roll.get_roll_list()
    # print(roll_list)
    # 添加roll饰品
    for roll in roll_list:
        print(roll["title"])
        gift_config_list = auto_create_roll.gift_config[roll["title"]]
        for gift_config in gift_config_list:
            gift_config["rollId"] = roll["id"]
            response = auto_create_roll.add_gift(gift_config)
            print(response)
        # 开启roll房间
        auto_create_roll.open_roll(roll["id"])
        time.sleep(1)


if __name__ == '__main__':
    create_roll()
